package com.polaris.live.ui.me

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.polaris.live.adapter.level.MeCharmAdapter
import com.polaris.live.adapter.level.MeCharmRichBannerAdapter
import com.polaris.live.adapter.level.MeCharmTempLevelAdapter
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.ext.dp
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbFragment
import com.polaris.live.common.network.parseState
import com.polaris.live.databinding.FragmentMeCharmBinding
import com.polaris.live.resp.bean.LevelUpRewardBean
import com.polaris.live.utils.RichCharmImgUtil
import com.polaris.live.viewmodel.me.RichCharmViewModel
import com.zhpan.indicator.enums.IndicatorSlideMode

/**
 * MeCharmFragment
 *
 * @author Created by 长空 on 2023/10/24/024 15:13
 */
class MeCharmFragment : BaseVbFragment<RichCharmViewModel, FragmentMeCharmBinding>() {

    private val mAdapter: MeCharmAdapter by lazy {
        MeCharmAdapter()
    }

    private val mLevelAdapter by lazy { MeCharmTempLevelAdapter() }

    private val mRewardList = mutableListOf<LevelUpRewardBean>()

    private val mBannerAdapter by lazy { MeCharmRichBannerAdapter() }

    private var mNowRichLevel = 0 //当前等级

    @SuppressLint("SetTextI18n")
    override fun initView(savedInstanceState: Bundle?) {
        UserManager.getUser().account?.let {
            val (charmLevel, charmNextNum, charmImage) = RichCharmImgUtil.getCharmImg(it.charms)
            val charmNum = RichCharmImgUtil.getCharmNum(it.charms)
            mNowRichLevel = charmLevel
            mBinding.tvLevel.text = "Lv.${charmLevel}"

            val currentLevel = if (charmLevel >= 15) {
                charmLevel - 1
            } else {
                charmLevel
            }
            mBinding.tvLevelStart.text = "Lv.${currentLevel}"
            mBinding.tvLevelEnd.text = "Lv.${currentLevel + 1}"

            mBinding.ivCharm.setImageResource(charmImage)

            val charm = it.charms - charmNum
            val totalCharm = charmNextNum - charmNum
            if (totalCharm > 0) {
                mBinding.progressBar.progress = (charm.toInt() * 100) / totalCharm
            } else {
                mBinding.progressBar.progress = 100
            }
            if (it.charms < charmNextNum) {
                mBinding.tvDiamond.text = (charmNextNum - it.charms).toString()
            } else {
                mBinding.tvDiamond.text = "0"
            }
        }

        mBinding.recyclerView.apply {
            layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
            adapter = mAdapter
        }
        mBinding.levelRecycler.apply {
            layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
            adapter = mLevelAdapter
        }
        mBinding.levelBanner.apply {
            registerLifecycleObserver(lifecycle)
            setAdapter(mBannerAdapter)
            setIndicatorSlideMode(IndicatorSlideMode.NORMAL)
            setIndicatorVisibility(View.GONE)
            setRoundCorner(12.dp)
            setAutoPlay(false)
            setCanLoop(false)
            registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
                override fun onPageSelected(position: Int) {
                    super.onPageSelected(position)
                    val isFirstItem = position == 0
                    val isLastItem = position == mBannerAdapter.itemCount - 1

                    mBinding.ivLeft.visibility = if (isFirstItem) View.GONE else View.VISIBLE
                    mBinding.ivRight.visibility = if (isLastItem) View.GONE else View.VISIBLE
                }
            })
        }
        mBinding.ivLeft.setOnSingleClickListener {
            val getNow = mBinding.levelBanner.currentItem
            if (getNow - 1 >= 0) {
                mBinding.levelBanner.setCurrentItem(getNow - 1, true)
            }
        }
        mBinding.ivRight.setOnSingleClickListener {
            val getNow = mBinding.levelBanner.currentItem
            if (getNow + 1 <= mBannerAdapter.itemCount) {
                mBinding.levelBanner.setCurrentItem(getNow + 1, true)
            }
        }
        mViewModel.getRichCharmRule()
        initObserver()
    }

    private fun initObserver() {
        mViewModel.mRichCharmLiveData.observe(this) { resultState ->
            mBinding.loadingView.visibility = View.GONE
            parseState(resultState, {
                mBinding.llBottom.visibility = View.VISIBLE
                val mutableList = it.charmLevel
                val sortedList = mutableListOf<LevelUpRewardBean>()
                it.charmLevelRewardExplains.forEach { (t, u) ->
                    sortedList.add(LevelUpRewardBean(t.toInt(), u))
                }
                mutableList?.forEach { cil ->
                    it.charmLevelRewardExplains.forEach { (t, u) ->
                        if (t.toInt() == cil.level) {
                            val ls = mutableListOf<String>()
                            u.forEach { str ->
                                ls.add(str.title)
                                cil.privilege = ls
                            }
                        }
                    }
                }
                mRewardList.addAll(sortedList.sortedWith(compareBy { it.level }))
                mAdapter.setList(mutableList)
                mLevelAdapter.setList(mRewardList)
                var data = mRewardList.getOrNull(0)?.rewardVo
                if (data == null) {
                    mBinding.llDressUp.visibility = View.GONE
                    return@parseState
                }
                if (mNowRichLevel > 0) {
                    var showIndex = 0
                    mRewardList.forEachIndexed { index, levelUpRewardBean ->
                        if (levelUpRewardBean.level == mNowRichLevel) {
                            showIndex = index
                        }
                    }
                    data = mRewardList.getOrNull(showIndex)?.rewardVo
                    mLevelAdapter.setSelect(showIndex)
                    mBinding.levelRecycler.scrollToPosition(showIndex)
                }
                mBinding.levelBanner.create(data)
                isShowLeftRight()
            }, {
                mBinding.errorView.visibility = View.VISIBLE
                mBinding.consDetail.visibility = View.GONE
                mBinding.errorView.setText(it.errorMsg)
            })
        }

        mLevelAdapter.setOnItemClickListener { adapter, view, position ->
            mLevelAdapter.setSelect(position)
            val data = mRewardList.getOrNull(position)?.rewardVo ?: return@setOnItemClickListener
            mBinding.levelBanner.create(data)
            isShowLeftRight()
        }
    }

    private fun isShowLeftRight() {
        if (mBannerAdapter.itemCount <= 1) {
            mBinding.ivLeft.visibility = View.GONE
            mBinding.ivRight.visibility = View.GONE
        } else {
            mBinding.ivRight.visibility = View.VISIBLE
        }
    }
}